package student.Dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.mysql.jdbc.Statement;

import student.base.Student;

public class StudentDaoImpl implements StudentDao {
	protected Logger logger = LogManager.getLogger(this.getClass().getName());
	Connection conn;
	PreparedStatement st;
	ResultSet rs;
	private String driver;
	private String url;
	private String user;
	private String pass;
	List<Student> students = null;

	public StudentDaoImpl() throws FileNotFoundException, IOException, ClassNotFoundException {
		this.initParam("mysql.ini");
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, pass);
			st = conn.prepareStatement("INSERT INTO STU VALUE(NULL,?,?,?)");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void initParam(String paramfile) throws FileNotFoundException, IOException {
		Properties props = new Properties();
		props.load(new FileInputStream(paramfile));
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		pass = props.getProperty("pass");
	}

	@Override
	public void leadingIn(String fileName) throws FileNotFoundException {
		File file = new File(fileName);
		InputStream input = new FileInputStream(file);
		XSSFWorkbook wb = null;
		try {
			wb = new XSSFWorkbook(input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		XSSFSheet sheet = wb.getSheetAt(1);
		try {
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				for (int j = 0; j < row.getLastCellNum(); j++) {
					Cell cell = row.getCell(j);
					if (cell != null) {
						cell.setCellType(CellType.STRING);
						String value = String.valueOf(row.getCell(j).getStringCellValue());
						if (j == 0)
							st.setString(j + 2, value);
						if (j == 1)
							st.setString(j + 2, value);
						if (j == 2)
							st.setString(j - 1, value);
					}
				}
				st.executeUpdate();// 传入数据库
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void leadingOut() throws FileNotFoundException, IOException, SQLException {
		this.initParam("mysql.ini");
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, pass);
			rs = st.executeQuery("select id ,class,code, fullname from stu");
			while (rs.next()) {
				this.logger.info(rs.getString(1) + "\t\n" + rs.getString(2) + "\t\n" + rs.getString(3) + "\t\n"
						+ rs.getString(4));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			rs.close();
			st.close();
			conn.close();
		}
	}

	@Override
	public void create(Student student) {
		try {
			String sql = "INSERT INTO STU( ID , CLASS , CODE , FULLNAME ) VALUES(" + null + ",'"
					+ student.getClassAndGrades() + "','" + student.getCode() + "','" + student.getFullName() + "')";
			logger.debug(student);
			@SuppressWarnings("unused")
			int result = st.executeUpdate(sql);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void remove(String code) {
		try {
			String sql = "DELETE FROM STU WHERE CODE = " + code;
			logger.debug("刪除记录成功！");
			@SuppressWarnings("unused")
			int result = st.executeUpdate(sql);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void update() throws SQLException {
		String change = "update stu.stu set fullname=? where id=?";
		PreparedStatement preparedStatement = conn.prepareStatement(change);

		String id, name;
		System.out.println("请输入需要修改名字的成员学号：");
		@SuppressWarnings("resource")
		Scanner num = new Scanner(System.in);
		id = num.next();

		System.out.println("请输入修改后的名字：");
		name = num.next();

		preparedStatement.setString(1, name);
		preparedStatement.setString(2, id);
		preparedStatement.execute();

		System.out.println("修改成功！...");

		@SuppressWarnings("unused")
		Statement statement = (Statement) conn.createStatement();
		ResultSet resultSet = preparedStatement.executeQuery("select * from stu.stu");
		while (resultSet.next()) {
			System.out.println(resultSet.getString("ID") + " " + resultSet.getString("CLASS") + " "
					+ resultSet.getString("CODE") + " " + resultSet.getString("FULLNAME"));
		}
		resultSet.close();
		preparedStatement.close();
		conn.close();

	}

	@Override
	public Student findByName(String name) {
		Student student = null;
		try {
			String selectSQL = "SELECT ID, CLASS, CODE, FULLNAME FROM STU WHERE FULLNAME =  " + name;
			ResultSet rs = this.st.executeQuery(selectSQL);
			while (rs.next()) {
				student = new Student();
				student.setId(rs.getLong("ID"));
				student.setClassAndGrades(rs.getString("CLASS"));
				student.setCode(rs.getString("CODE"));
				student.setFullName(rs.getString("FULLNAME"));
				if (student.getFullName() == name) {
					logger.info("found student:" + student);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return student;
	}

	@Override
	public Student findByCode(String code) {
		Student student = null;
		try {
			String selectSQL = "SELECT ID, CLASS, CODE, FULLNAME FROM STU WHERE CODE =  " + code;
			ResultSet rs = this.st.executeQuery(selectSQL);
			while (rs.next()) {
				student = new Student();
				student.setId(rs.getLong("ID"));
				student.setClassAndGrades(rs.getString("CLASS"));
				student.setCode(rs.getString("CODE"));
				student.setFullName(rs.getString("FULLNAME"));
				if (student.getCode() == code) {
					logger.info("found student:" + student);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return student;
	}
}
